<script setup lang='ts'>
import { ref,reactive, nextTick, onMounted, onBeforeUnmount, markRaw } from 'vue'
import setUpTime from '@/utils/setUpTime'
import * as echarts from 'echarts'
import { getBarWheelMachine,GetBarWheelMachineWorkAll } from '@/api/publicApi'
import RedirectIndex from '@/views/Redirect/RedirectIndex.vue'

// echart实例icTime
const myEcharts = echarts
const chart1 = ref()
const chart2 = ref()
const chart3 = ref()

// 定义变量
const value = ref('')
// 选择的机器
const barWheelVal = ref('')

// 网络请求参数
const params = reactive({
  HarborCode: '',
  CompanyCode: '',
  BarWheelMachineCode: '',
  MaxResultCount: 0,
  StartTime: '',
  EndTime: ''
})

// 机器选择数据源
const barWheelMachineChangeList:any = ref([])

// 左侧柱状图数据
interface analysisSeriesInter{
  stockWeight: any,
  takeWeight: any
}
const analysisSeries: analysisSeriesInter = reactive( {
  stockWeight: [],
  takeWeight: []
})

// 机器各状态时间统计
interface timeInter {
  outWorkTime: any,
  outIdleTime: any,
  outDowntime: any,
}
const barStaticTime: timeInter = reactive({
  outWorkTime: [], //工作时间
  outIdleTime: [], //空闲时间
  outDowntime: [] //停机时间
})

// 饼状图各状态机器时间
const sumStaticTime: timeInter = reactive( {
  outWorkTime: [], //工作时间
  outIdleTime: [], //空闲时间
  outDowntime: [] //停机时间
})

// 柱状图X轴文本
const analysisxAxis:any = ref([])
const option1 = {
  title: {
    text: '堆取料累计分析',
    left: 'left',
    textStyle: {
      color: '#fff',
      fontSize: '0.975rem'
    }
  },
  grid: {
    left: '0%',
    right: '0',
    bottom: '0%',
    containLabel: true
  },
  legend: {
    right: 'right',
    textStyle: {
      color: '#fff'
    }
  },
  tooltip: {},
  xAxis: {
    type: 'category',
    axisLabel: {
      textStyle: {
        color: '#fff'
      }
    },
    data: [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri' ]
  },
  yAxis: {
    axisLabel: {
      textStyle: {
        color: '#fff'
      }
    }
  },
  series: [
    {
      name: '堆料量(吨)',
      type: 'bar',
      barWidth: 36,
      barCategoryGap: 12,
      data: [ '2012', '2013', '2014', '2015', '2016' ],
      itemStyle: {
        // 柱体渐变色
        color: new myEcharts.graphic.LinearGradient(0, 0, 0, 3, [
          {
            offset: 0,
            color: 'rgba(50, 161, 255, 0.7)'
          },
          {
            offset: 1,
            color: 'red'
          }
        ])
      }
    },
    {
      name: '取料量(吨)',
      type: 'bar',
      barWidth: 36,
      barCategoryGap: 12,
      data: [ '2000', '1986', '1764', '2150', '2010'  ],
      itemStyle: {
        // 柱体渐变色
        color: new myEcharts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0.3,
            color: 'rgba(216, 143, 80, 1)'
          },
          {
            offset: 1,
            color: 'rgba(241, 116, 39, 0.46)'
          }
        ])
      }
    }
  ]
}
const option2 = {
  title: {
    text: '工作累计分析',
    // subtext: 'Fake Data',
    left: 'center',
    textStyle: {
      color: '#fff',
      fontSize: '0.975rem'
    }
  },
  tooltip: {
    trigger: 'item',

    formatter: function (params) {
      // 
      return (
        '<div>' +
        params.marker +
        '<span>' +
        params.data.name +
        '</span>' +
        '  ' +
        params.data.value +
        '  (小时)' +
        '</div>'
      )
    }
  },
  legend: {
    left: 'center',
    bottom: '2%',
    textStyle: {
      color: '#fff'
    }
  },
  series: [
    {
      // name: 'Access From',
      type: 'pie',
      radius: '50%',
      data: [
        {
          value: 15,
          name: '工作',
          itemStyle: { color: '#ed7d31' }
        },
        {
          value: 12,
          name: '空闲',
          itemStyle: { color: '#59ebe8' }
        },
        {
          value: 7,
          name: '停机',
          itemStyle: { color: '#ccc' }
        }
      ]
    }
  ]
}
const option3 = {
  title: {
    text: '一周使用率分析',
    left: 'left',
    textStyle: {
      color: '#fff',
      fontSize: '0.975rem'
    }
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    // right: "right",
    textStyle: {
      color: '#fff'
    }
    // data: ['工作','空闲','停机']
  },

  grid: {
    left: '0%',
    right: '0%',
    bottom: '0%',
    containLabel: true
  },

  dataZoom: [
    {
      type: 'inside'
    }
  ],
  xAxis: {
    type: 'category',
    // boundaryGap: false,
    data: [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ],
    axisLabel: {
      textStyle: {
        color: '#fff'
      }
    }
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      textStyle: {
        color: '#fff'
      }
    }
  },
  series: [
    {
      name: '工作(小时)',
      type: 'line',
      itemStyle: { color: '#ed7d31' },
      data: [ 120, 132, 101, 134, 90, 230, 210 ]
    },
    {
      name: '空闲(小时)',
      type: 'line',
      itemStyle: { color: '#59ebe8' },
      data: [ 220, 182, 191, 234, 290, 330, 310 ]
    },
    {
      name: '停机(小时)',
      type: 'line',
      itemStyle: { color: '#d6d6d6' },
      data: [ 150, 232, 201, 154, 190, 330, 410 ]
    }
  ]
}

onMounted(() => {
  // initChart()
  let BarWheelMachineCode =
    localStorage.BarWheelMachineCode
      ? localStorage.BarWheelMachineCode
      : null
  let time = setUpTime.getDay()
  params.BarWheelMachineCode = BarWheelMachineCode,
  params.MaxResultCount = 15,
  params.StartTime = time[6] + ' ' + '00:00:00',
  params.EndTime = time[0] + ' ' + '23:59:59',

  // 获取堆取料机
  getBarWheelMachine(params).then(res => {
    
    barWheelMachineChangeList.value = []
    res.result.items.forEach(item => {
      if (item.gltfName.indexOf('堆取料机') > -1 || item.gltfName.indexOf('取料机') > -1) {
        barWheelMachineChangeList.value.push(item)
      }
    })
    barWheelMachineChangeList.value = barWheelMachineChangeList.value.sort(
      (a, b) => {
        return a.id - b.id
      }
    )
    barWheelVal.value = barWheelMachineChangeList.value[0].code
    getList()
  })
  
})
// 选择机器
const barWheelMachineChange = (val:any) => {
  params.BarWheelMachineCode = val
  console.log(val)
  getList()
}
// 获取图表信息
const getList = async() => {
  barStaticTime.outWorkTime = []
  barStaticTime.outIdleTime = []
  barStaticTime.outDowntime = []
  analysisSeries.stockWeight = []
  analysisSeries.takeWeight = []
  analysisxAxis.value = []
  sumStaticTime.outWorkTime = []
  sumStaticTime.outIdleTime = []
  sumStaticTime.outDowntime = []
  // 获取每天统计信息
  let res = await GetBarWheelMachineWorkAll({ BarWheelMachineCode: barWheelVal })
  
  if (res.result.items && res.result.items.length > 1) {
    let IdleTimeSum = 0
    let DowntimeSum = 0
    let WorkTimeSum = 0
    res.result.items.forEach(item => {
      analysisSeries.stockWeight.push(item.stockWeight)
      analysisSeries.takeWeight.push(item.takeWeight)
      analysisxAxis.value.push(item.lastModificationTime.slice(0, 10))

      // //获取工作时间
      // 空闲时间   获取七天的工作状态

      barStaticTime.outIdleTime.push(item.outIdleTime.toFixed(1))
      //停机时间
      barStaticTime.outDowntime.push(item.outDowntime.toFixed(1))
      // 工作时间
      barStaticTime.outWorkTime.push(item.outWorkTime.toFixed(1))
      // 计算七天总工作时长
      IdleTimeSum += item.outIdleTime.toFixed(3) * 1000
      DowntimeSum += item.outDowntime.toFixed(3) * 1000
      WorkTimeSum += item.outWorkTime.toFixed(3) * 1000
    })
    sumStaticTime.outWorkTime = (WorkTimeSum / 1000).toFixed(1) //工作时间
    sumStaticTime.outIdleTime = (IdleTimeSum / 1000).toFixed(1) //空闲时间
    sumStaticTime.outDowntime = (DowntimeSum / 1000).toFixed(1) //停机时间
  }
  initChart()
}
// 初始化Echarts图表
const initChart = () => {
  nextTick(() => {
    chart1.value = markRaw(myEcharts.init(document.getElementById('materialAnalysis')))
    option1.xAxis.data = analysisxAxis.value
    option1.series[0].data = analysisSeries.stockWeight
    option1.series[1].data = analysisSeries.takeWeight
    chart1.value.setOption(option1)

    chart2.value = markRaw(myEcharts.init(document.getElementById('workAnalysis')))
    option2.series[0].data[0].value = sumStaticTime.outWorkTime
    option2.series[0].data[1].value = sumStaticTime.outIdleTime
    option2.series[0].data[2].value = sumStaticTime.outDowntime
    chart2.value.setOption(option2)
    
    chart3.value = markRaw(myEcharts.init(document.getElementById('usageAnalysis')))
    option3.xAxis.data = analysisxAxis.value
    option3.series[0].data = barStaticTime.outWorkTime
    option3.series[1].data = barStaticTime.outIdleTime
    option3.series[2].data = barStaticTime.outDowntime
    chart3.value.setOption(option3)
    console.log('获取当前设备的数据--->', option1, option2, option3)
  })
}

// 跳转
const goToHome = () => {
  console.log('跳转到生产信息统计')
  let barWheelObj = barWheelMachineChangeList.value.find(
    item => item.code === barWheelVal.value
  )
  let path
  if (barWheelObj.gltfName.split('h')[1] === '取料机') {
    path = '_three_dimensional-Q'
  } else if (barWheelObj.gltfName.value.split('h')[1] === '堆料机') {
    path = '_three_dimensional-D'
  } else {
    path = '_three_dimensional-DQ'
  }
  // setTimeout(() => {
  //   Bus.$emit('mainLeftMenuChange')

  //   localStorage.ResetRouter = this.$router.currentRoute.path
  //   Bus.$emit('ruterChange')
  // }, 200)
}

// 销毁Echarts
onBeforeUnmount(() => {
  chart1.value.dispose()
  chart2.value.dispose()
  chart3.value.dispose()
})
</script>

<template>
  <div class="bottom-info-main-box">
    <div class="title-box">
      <span @click="goToHome">生产信息统计</span>
      <div class="select-box">
        <el-select
          v-model="barWheelVal"
          placeholder="Select"
          size="small"
          @change="barWheelMachineChange"
        >
          <el-option
            v-for="item in barWheelMachineChangeList"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </div>
    </div>
    <div class="echarts-box">
      <div id="materialAnalysis" />
      <div id="workAnalysis" />
      <div id="usageAnalysis" />
    </div>
  </div>
</template>

<style scoped lang=scss>
.bottom-info-main-box {
  width: 100%;
  height: 100%;
  background-image: url("../../../assets/imgs/border.png");
  background-size: 100% 100%;

  .title-box {
    display: flex;
    align-items: center;
    width: 100%;
    height: 28px;
    padding-top: 25px;
    padding-left: 48px;
    color: #fff;

    /* border: 1px solid red; */
    >span {
      &:hover {
        cursor: pointer;
      }
    }

    .select-box {
      margin-left: 50px;
    }
  }

  .echarts-box {
    display: flex;
    justify-content: space-around;
    width: 100%;
    height: calc(100% - 53px);
    margin-top: 25px;
    padding: 0 30px;

    /* border: 1px solid red; */

    >div {
      height: 90%;

      /* border: 1px solid green; */
    }

    /* stylelint-disable-next-line selector-id-pattern */
    #materialAnalysis {
      width: 36%;
    }

    /* stylelint-disable-next-line selector-id-pattern */
    #workAnalysis {
      width: 25%;
    }

    /* stylelint-disable-next-line selector-id-pattern */
    #usageAnalysis {
      width: 36%;
    }
  }
}
</style>